<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class ImageProcess{
  var $imagePath;
  var $width;
  var $height;
  var $proportion;
  var $bgcolor;
  var $item_id;
  var $resize_folder;
  var $url_to_resize;

  public function __construct($imagePath, $resize_folder,$url_to_resize,$item_id,$width, $height, $proportion = 'bestfit' , $bgcolor = '#FFFFFF')
  {
      $this->imagePath = $imagePath;
      $this->resize_folder = $resize_folder;
      $this->url_to_resize = $url_to_resize;
      $this->width = $width;
      $this->height = $height;
      $this->proportion = $proportion;
      $this->bgcolor = hexdec($bgcolor);   
  }

  function getThumbnail()
	{
   	$img_name   = pathinfo($this->imagePath, PATHINFO_FILENAME);
		$img_ext    = pathinfo($this->imagePath, PATHINFO_EXTENSION);
		$img_path   = JPATH_BASE  . DS . str_replace('/', DS, $this->imagePath);
		$size 	    = @getimagesize($img_path);
		$errors = array();
		if(!$size){
			$errors[] = 'There was a problem loading image ' . $img_name . '.' . $img_ext;

		}
    else {
			$sub_folder = '0' . substr($this->item_id, -1);

			$origw = $size[0];
			$origh = $size[1];
			if( ($origw < $this->width && $origh < $this->height)) {
				$width = $origw;
				$height = $origh;
			}
     
			$prefix = substr($this->proportion,0,1) . "_" . $this->width ."_" . $this->height . "_" . $this->bgcolor . "_" . $this->item_id . "_";

			$thumb_file = $prefix . str_replace(array( JPATH_ROOT, ':', '/', '\\', '?', '&', '%20', ' '),  '_' ,$img_name . '.' . $img_ext);
      $thumb_file = strtolower($thumb_file);
      $folderPath = $this->resize_folder;
     
		 	if(!JFolder::exists($folderPath)){
		 		JFolder::create($folderPath);        
		 	}
      $folderPath = $this->resize_folder . DS . 'thumbs';
      if(!JFolder::exists($folderPath)){
          JFolder::create($folderPath);
      }
			$thumb_path = $this->resize_folder . DS . 'thumbs' . DS  . $thumb_file;
			$attribs = array();
			if(file_exists($thumb_path))	{
				$size = @getimagesize($thumb_path);
				if($size) {
					$attribs['width']  = $size[0];
					$attribs['height'] = $size[1];
				}
			} else {
        $width = $this->width;
        $height = $this->height;
				$this->calculateSize($origw, $origh, $width, $height, $this->proportion, $newwidth, $newheight, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
				switch(strtolower($size['mime'])) {
					case 'image/png':
						$imagecreatefrom = "imagecreatefrompng";
						break;
					case 'image/gif':
						$imagecreatefrom = "imagecreatefromgif";
						break;
					case 'image/jpeg':
						$imagecreatefrom = "imagecreatefromjpeg";
						break;
					default:
						$errors[] = "Unsupported image type $img_name.$img_ext ".$size['mime'];
				}
        
				if ( !function_exists ( $imagecreatefrom ) ) {
					$errors[] = "Failed to process $img_name.$img_ext. Function $imagecreatefrom doesn't exist.";
				}

				$src_img = $imagecreatefrom($img_path);
        
				if (!$src_img) {
					$errors[] = "There was a problem to process image $img_name.$img_ext ".$size['mime'];
				}

				$dst_img = imagecreatetruecolor($width, $height);

				// $bgcolor = imagecolorallocatealpha($image, 200, 200, 200, 127);

				imagefill( $dst_img, 0,0, $this->bgcolor);
				if ( $this->proportion == 'transparent' ) {
					imagecolortransparent($dst_img, $this->bgcolor);
				}

				imagecopyresampled($dst_img,$src_img, $dst_x, $dst_y, $src_x, $src_y, $newwidth, $newheight, $src_w, $src_h);
       
				switch(strtolower($img_ext)) {
					case 'png':
						$imagefunction = "imagepng";
						break;
					case 'gif':
						$imagefunction = "imagegif";
						break;
					default:
						$imagefunction = "imagejpeg";
				}
       
				if($imagefunction=='imagejpeg') {
					$result = @$imagefunction($dst_img, $thumb_path, 80 );
				} else {
					$result = @$imagefunction($dst_img, $thumb_path);
				}
				imagedestroy($src_img);
				if(!$result) {
					if(!$disablepermissionwarning) {
					$errors[] = 'Could not create image:<br />' . $thumb_path . '.<br /> Check if the folder exists and if you have write permissions:<br /> ' . dirname(__FILE__) . '/thumbs/' . $sub_folder;
					}
					$disablepermissionwarning = true;
				} else {
					imagedestroy($dst_img);
				}
			}
		}

		if (count($errors)) {
			JError::raiseWarning(404, implode("\n", $errors));
			return false;
		}
    
		$image = $this->url_to_resize . 'thumbs/' . basename($thumb_path);

		return  JHTML::_('image', $image, '', $attribs);
  }


  public function calculateSize($origw, $origh, &$width, &$height, &$proportion, &$newwidth, &$newheight, &$dst_x, &$dst_y, &$src_x, &$src_y, &$src_w, &$src_h)
  {
		if(!$width ) {
			$width = $origw;
		}

		if(!$height ) {
			$height = $origh;
		}

		if ( $height > $origh ) {
			$newheight = $origh;
			$height = $origh;
		} else {
			$newheight = $height;
		}

		if ( $width > $origw ) {
			$newwidth = $origw;
			$width = $origw;
		} else {
			$newwidth = $width;
		}

		$dst_x = $dst_y = $src_x = $src_y = 0;

		switch($proportion) {
			case 'fill':
			case 'transparent':
				$xscale=$origw/$width;
				$yscale=$origh/$height;

				if ($yscale<$xscale){
					$newheight =  round($origh/$origw*$width);
					$dst_y = round(($height - $newheight)/2);
				} else {
					$newwidth = round($origw/$origh*$height);
					$dst_x = round(($width - $newwidth)/2);

				}

				$src_w = $origw;
				$src_h = $origh;
				break;

			case 'crop':

				$ratio_orig = $origw/$origh;
				$ratio = $width/$height;
				if ( $ratio > $ratio_orig) {
					$newheight = round($width/$ratio_orig);
					$newwidth = $width;
				} else {
					$newwidth = round($height*$ratio_orig);
					$newheight = $height;
				}

				$src_x = ($newwidth-$width)/2;
				$src_y = ($newheight-$height)/2;
				$src_w = $origw;
				$src_h = $origh;
				break;

 			case 'only_cut':
				// }
				$src_x = round(($origw-$newwidth)/2);
				$src_y = round(($origh-$newheight)/2);
				$src_w = $newwidth;
				$src_h = $newheight;

				break;

			case 'bestfit':
				$xscale=$origw/$width;
				$yscale=$origh/$height;

				if ($yscale<$xscale){
					$newheight = $height = round($width / ($origw / $origh));
				}
				else {
					$newwidth = $width = round($height * ($origw / $origh));
				}
				$src_w = $origw;
				$src_h = $origh;

				break;
			}
	}
}

?>
